﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FuturamaKassa {
    static class RFIDFunctions {

        private static readonly byte STX = 0x02;
        private static readonly byte EXT = 0x03;

        public static byte calcChecksum(byte[] array) {

            byte a = 0x00;

            for (int i = 0; i < (array.Length - 1); i++ ) {
                a ^= array[i];
            }

            return a;
        }
        
        public static List<string> SplitByNumber(string value, int chunkSize) {
            List<string> triplets = new List<string>();
            for (int i = 0; i < value.Length; i += chunkSize)
                if (i + chunkSize > value.Length)
                    triplets.Add(value.Substring(i));
                else
                    triplets.Add(value.Substring(i, chunkSize));

            return triplets;
        }


        public static List<string> revertBitOrder(List<string> list) {

            List<string> returnList = new List<string>();

            foreach (string s in list) {

                char[] array = s.ToCharArray();
                char[] newArray = new char[array.Length];

                for (int i = 0; i < array.Length; i++) {

                    newArray[0 + i] = array[(array.Length - 2) - i];
                    newArray[1 + i] = array[(array.Length - 1) - i];

                    i++;
                }

                returnList.Add(new string(newArray));
            }

            return returnList;
        }

        /**
         * Function to build a byte array from a command string.
         * 
         */
        public static byte[] buildCommand(String command) {

            byte[] commandArray = Encoding.ASCII.GetBytes(command);
            byte[] array = new byte[3 + command.Length];

            array[0] = STX;
            array[array.Length - 2] = EXT;

            for (int i = 0; i < commandArray.Length; i++) {
                array[i + 1] = commandArray[i];
            }

            array[array.Length - 1] = RFIDFunctions.calcChecksum(array);

            return array;
        }
    }
}
